<?php

namespace Administrator\Model;

use Zend\Db\Sql\Sql;
use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;

class ResourceTable extends AbstractTableGateway
{

    public $table = 'resource';
    protected $tableGateway;

    public function __construct(Adapter $adapter,TableGateway $tableGateway = null)
    {
        $this->adapter = $adapter;
        $this->resultSetPrototype = new ResultSet(ResultSet::TYPE_ARRAY);
        $this->initialize();
        $this->tableGateway = $tableGateway;
    }

    public function getAllResources()
    {
        try {
            $sql = new Sql($this->getAdapter());
            $select = $sql->select()->from(array(
                'rs' => $this->table
            ));
            $select->order('id DESC');
            $select->columns(array(
                'id',
                'resource_name'
            ));
            $statement = $sql->prepareStatementForSqlObject($select);
            $resources = $this->resultSetPrototype->initialize($statement->execute())
                ->toArray();
            return $resources;
        } catch (\Exception $e) {
            throw new \Exception($e->getPrevious()->getMessage());
        }
    }
    
    public function countResources(){
    	return $this->tableGateway->select()->count();
    }
    
    public function saveResource(Resource $Resourcedata,$id)
    {
    	if ($id == 0) {
    		$data = array(
    				'resource_name' => $Resourcedata->name_resource ,
    		);
    		$this->tableGateway->insert($data);
    	}else {
    		$data = array(
    				'resource_name' => $Resourcedata->name_resource ,
    		);
    				if ($this->getResource($id)) {
    					$this->tableGateway->update($data, array('id' => $id));
    					
    				} else {
    					throw new \Exception('resource id does not exist');
    				}
    	}
    }
    
    public function getResource($id)
    {
    	$id  = (int) $id;
    	try {
    		$select = $this->tableGateway->getSql()->select();
    		$select->where(array('id' => $id));
    		$resultSet = $this->tableGateway->selectWith ( $select );
    		$row = $resultSet->current();
    
    		$row->name_resource = $row->resource_name;
    
    		return $row;
    	} catch (\Exception $e) {
    		throw new \Exception($e->getPrevious()->getMessage());
    	}
    }
    
    public function deleteResource($id){
    	$this->tableGateway->delete(array('id'=>$id));
    }
}
